package com.bridgeintelligent.tag.customer.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.customer.constant.PublicConstant;
import com.bridgeintelligent.tag.customer.entity.CustomersCodes;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.entity.ShareRelation;
import com.bridgeintelligent.tag.customer.exception.CustomersException;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.mapper.CustomersShareMapper;
import com.bridgeintelligent.tag.customer.mapper.QueryModelMapper;
import com.bridgeintelligent.tag.customer.mapper.RecordMapper;
import com.bridgeintelligent.tag.customer.model.CustomerModel;
import com.bridgeintelligent.tag.customer.model.IndexInfoModel;
import com.bridgeintelligent.tag.customer.model.ShareModel;
import com.bridgeintelligent.tag.customer.pojo.*;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.FieldHandler;
import com.bridgeintelligent.tag.utils.IdWorker;
import com.bridgeintelligent.tag.webserver.dim.query.api.CustomerGroupRsp;
import com.bridgeintelligent.tag.webserver.dim.query.api.service.IQueryService;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.bridgeintelligent.tag.customer.constant.PublicConstant.*;

/**
 * 客群服务层接口实现
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Slf4j
public class CustomersServiceImpl implements CustomersService {

    private CustomersMapper customersMapper;
    private QueryModelMapper queryModelMapper;
    private RecordMapper recordMapper;
    private CustomersShareMapper customersShareMapper;
    private IQueryService queryService;
    public static final Pattern pattern = Pattern.compile("[0-9]*");




    /**
     * 校验客群名是否重复
     *
     * @param customersName
     * @return
     */
    @Override
    public boolean checkCustomersName(String customersName) {
        int count = customersMapper.checkCustomersName(customersName);
        if (count == 1) {
            return false;
        }
        return true;
    }

    /**
     * 根据客群id查找客群名称
     *
     * @param customersId
     * @return
     */
    @Override
    public String findCustomersNameById(String customersId) {
        String customersName = customersMapper.findCustomersNameById(customersId);
        return customersName;
    }

    /**
     * 分页条件查询客群列表
     * @param model 查询
     * @return 结果
     */
    @Override
    public Result list(ListQueryModel model) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Map map = new HashMap();
        map.put("approvalStatus",model.getApprovalStatus());
        map.put("userId", user.getUserId());
        map.put("customersName", model.getCustomersName());
        map.put("status", model.getStatus());
        map.put("createTimeStart", model.getCreateTimeStart());
        map.put("director", model.getDirector());
        if (model.getCreateTimeEnd() != null && !"".equals(model.getCreateTimeEnd())) {
            map.put("createTimeEnd", model.getCreateTimeEnd() + "23.59.59");
        }
        map.put("uptTimeStart", model.getUptTimeStart());
        if (model.getUptTimeEnd() != null && !"".equals(model.getUptTimeEnd())) {
            map.put("uptTimeEnd", model.getUptTimeEnd() + "23.59.59");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
        List<Customers> list = new ArrayList<>();
        if (FieldHandler.isUnionAdmin(user.getRoleId())){
            //如果是超管
            list = customersMapper.findUnionAdminList(map);
        }else{
            list = customersMapper.findList(map);
        }

        //获取索引信息
        List<IndexInfoModel> allIndex = customersMapper.findAllIndex();
        Map<String, String> toMap = allIndex.stream().collect(Collectors.toMap(IndexInfoModel::getIndexId, IndexInfoModel::getIndexName));
        if (CollectionUtils.isEmpty(toMap)){
            toMap = new HashMap<>();
        }

        if (list != null && !list.isEmpty()) {
            for (Customers customers : list) {
                //根据索引ID设置索引名字
                customers.setIndexName(toMap.get(customers.getIndexId()));
                if (CustomersCodes.STATUS_01.equals(customers.getStatus())) {
                    customers.setStatusName("有效");
                } else if (CustomersCodes.STATUS_02.equals(customers.getStatus())) {
                    customers.setStatusName("失效");
                }
                if ("1".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("未提交");
                } else if ("2".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("待审核");
                } else if ("3".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("驳回");
                } else if ("4".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("已通过");
                }
                if (temp.compareTo(customers.getCreateTime()) < 1) {
                    customers.setIsnew(true);
                } else {
                    customers.setIsnew(false);
                }

                Map map1 = new HashMap();
                map1.put("customersId", customers.getCustomersId());
                map1.put("workflowId", TagConstants.Workflow.ID_10010);
                CustomersApprovalRecord record = recordMapper.findDelById(map1);
                if (record == null ){
                    customers.setDelStatus("1");
                }else{
                    customers.setDelStatus(record.getApproverStatus());
                }
                customers.setIsAnalysis(isAnalysis(customers.getDimIds()));
            }
        }
        CustomersPage<Customers> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(model.getPageNumber());
        return new Result(CustomersCodes.SUCCESS, customersPage);
    }

    @Override
    public Result indexCustomerList(String indexId,String customersName) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        List<CustomerModel> list = new ArrayList<>();
        if (FieldHandler.isUnionAdmin(user.getRoleId())){
            //如果是超管
            list = customersMapper.indexAdminList(indexId,customersName);
        }else{
            list = customersMapper.indexCommonList(user.getUserId(),indexId,customersName);
        }
        return new Result(CustomersCodes.SUCCESS, list);
    }


    /**
     * 是否可以洞察
     * @param dimIds
     * @return 00 否 01 是
     */
    private String isAnalysis(String dimIds){
        if(StringUtils.isBlank(dimIds)){
            return "00";
        }
        List<String> list = JSON.parseArray(dimIds, String.class);
        if(CollectionUtils.isEmpty(list)){
            return "00";
        }
        int count = customersMapper.countNotFreeDim(list);
        if(count<=0){
            return "00";
        }
        return "01";
    }

    /**
     * 获取渠道列表
     *
     * @return
     */
    @Override
    public List<Channel> findAllChannel() {
        List<Channel> channelList = customersMapper.findAllChannel();
        return channelList;
    }


    /**
     * 新增客群
     *
     */
    @Override
    public void addCustomers(CustomersModel customersModel) {
        JSONObject queryCriteria = JSONObject.parseObject(customersModel.getQueryCriteria());
        Customers customers = new Customers();
        //设置id
        customers.setCustomersId(IDGenerator.gen());
        customers.setIndexId(customersModel.getIndexId());
        //默认启用
        customers.setStatus(CustomersCodes.STATUS_01);
        customers.setApprovalStatus("1");//创建成功后默认审批状态为未提交
        customers.setCustomersName(customersModel.getCustomersName());
        customers.setIsDel("00");
        customers.setCustomersDes(customersModel.getCustomersDes());
        customers.setDateType(customersModel.getDateType());
        customers.setIsMark(PublicConstant.ZERO);
        User user = TagSecurityHelper.currentUser();
        //负责人
        customers.setDirector(user.getName());
        //申请人
        customers.setOwnerId(user.getUserId());
        //创建时间,更新时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setCreateTime(sdf.format(new Date()));
        customers.setUptTime(sdf.format(new Date()));
        //设置客群与渠道的关联关系
        if (customersModel.getShareChannelIds() != null && customersModel.getShareChannelIds().length > 0) {
            setCustomersAndChannel(customers.getCustomersId(), customersModel.getShareChannelIds());
        }
        //客群的渠道信息
        String channelName = "";
        List<String> channelList = customersMapper.findChannelByCustomersId(customers.getCustomersId());
        if (channelList != null && channelList.size() > 0) {
            for (int i = 0; i < channelList.size(); i++) {
                if (i == 0) {
                    channelName = channelList.get(i);
                } else {
                    channelName += ("/" + channelList.get(i));
                }
            }
        }
        customers.setShareChannel(channelName);
        //保存查询条件
        QueryModel queryModel = JSON.toJavaObject(queryCriteria, QueryModel.class);
        queryModel.setId(IDGenerator.gen());
        queryModel.setCustomersId(customers.getCustomersId());
        queryModel.setDimIds(JSON.toJSONString(queryModel.getFields()));
        queryModelMapper.addQueryModel(queryModel);
        if (queryModel.getFilterGroup() == null) {
            throw new CustomersException(ExceptionCodes.CUSTOMERS_80003);
        }
        //新增条件组
        String parentId = "-";
        setFilterGroup(customers.getCustomersId(), queryModel.getFilterGroup(), parentId,customersModel.getDateType());
        //新增客群
        customersMapper.addCustomers(customers);
    }

    //新增条件组
    private void setFilterGroup(String customersId, FilterGroup children, String parentId,String dateType) {
        Filter filterSet;
        FilterGroup filterGroupSet;
        filterGroupSet = new FilterGroup();
        filterGroupSet.setId(IDGenerator.gen());
        filterGroupSet.setSymbol(children.getSymbol());
        filterGroupSet.setParentId(parentId);
        filterGroupSet.setCustomersId(customersId);
        filterGroupSet.setLocation(children.getLocation());
        //存到filterGroup表
        queryModelMapper.addFilterGroup(filterGroupSet);
        //filter
        if (children.getFilters() != null && !children.getFilters()
                                                      .isEmpty()) {
            for (Filter filter : children.getFilters()) {
                //先校验标签是否被停用
                Integer count = customersMapper.checkStop(filter.getDimId());
                if (count != null && count > 0){
                    throw new CustomersException(ExceptionCodes.DIMFREE_90005.args(filter.getDimName().toString()));
                }

                filterSet = new Filter();
                filterSet.setId(IDGenerator.gen());
                filterSet.setDimId(filter.getDimId());
                filterSet.setDimName(filter.getDimName());
                filterSet.setValueListStr(JSON.toJSONString(filter.getValueList()));
                filterSet.setType(filter.getType());
                filterSet.setClassify(filter.getClassify());
                filterSet.setDimLargeType(filter.getDimLargeType());
                filterSet.setTimeType(filter.isTimeType());
                filterSet.setDataDate(filter.getDataDate());
                if(dateType.equals("true")){
                    filterSet.setTimeType(true);
                    if("0".equals(filter.getDataDate())){
                        filterSet.setDataDate(customersMapper.findTime0(filter.getIndexId()));
                    } else{
                        filterSet.setDataDate(customersMapper.findTime(filter.getIndexId(),filter.getDataDate()));
                    }
                }
                filterSet.setIndexId(filter.getIndexId());
                //存入filter
                queryModelMapper.addFilter(filterSet);
                //设置与filterGroup关系
                Map<String, String> map = new HashMap<>();
                map.put("filter_id", filterSet.getId());
                map.put("filtergroup_id", filterGroupSet.getId());
                String id = IDGenerator.gen();
                map.put("id", id);
                //存入条件组和过滤条件关联关系
                queryModelMapper.addFilterAndFilterGroup(map);
            }
        }
        if (children.getChildren() != null && !children.getChildren()
                                                       .isEmpty()) {
            for (FilterGroup child : children.getChildren()) {
                setFilterGroup(customersId, child, filterGroupSet.getId(),dateType);
            }
        }
    }

    /**
     * 删除客群
     *
     * @param customersId
     */
    @Override
    public void delCustomers(String customersId) {
        //删除关联渠道
        //delCustomersAndChannel(customersId);
        //删除查询条件
        //delQueryModel(customersId);
        //删除客群
        //customersMapper.delCustomers(customersId);
        customersMapper.delUptCustomers(customersId);
    }

    //删除查询条件
    private void delQueryModel(String customersId) {
        //通过customersId查询filtergroup
        List<String> filtergroupIds = queryModelMapper.findFilterGroupBycustomersId(customersId);
        //通过filtergroupIds查询filterIds
        if (filtergroupIds != null && !filtergroupIds.isEmpty()) {
            for (String filtergroupId : filtergroupIds) {
                List<String> filterIds = queryModelMapper.findFilterIds(filtergroupId);
                //根据filterIds删除filter
                if (filterIds != null && !filterIds.isEmpty()) {
                    for (String filterId : filterIds) {
                        queryModelMapper.delFilterById(filterId);
                        //删除filtergroup与filter的关联关系
                        queryModelMapper.delFilterAndFilterGroup(filterId);
                    }
                }
            }
        }
        //删除filtergroup
        queryModelMapper.delFilterGroup(customersId);
        //删除queryModel
        queryModelMapper.delQueryModel(customersId);
    }

    /**
     * 修改客群
     *
     * @param customersId
     * @param customersName
     * @param customersDes
     * @param status
     * @param shareChannelIds
     * @param queryCriteria
     */
    @Override
    public void updateCustomers(String customersId, String customersName, String customersDes, String dateType, String status, String[] shareChannelIds, JSONObject queryCriteria,String indexId) {
        //修改客群与渠道的关联关系
        if (shareChannelIds != null) {
            //删除客群与渠道的关联关系
            delCustomersAndChannel(customersId);
            //设置客群与渠道的关联关系
            setCustomersAndChannel(customersId, shareChannelIds);
        }
        //修改客群
        Customers customers = new Customers();
        customers.setCustomersId(customersId);
        customers.setIndexId(indexId);
        customers.setStatus(status);
        customers.setCustomersName(customersName);
        customers.setCustomersDes(customersDes);
        customers.setDateType(dateType);
        customers.setIsMark(PublicConstant.ZERO);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setUptTime(sdf.format(new Date()));
        //客群的渠道信息
        String channelName = "";
        List<String> channelList = customersMapper.findChannelByCustomersId(customersId);
        if (channelList != null && channelList.size() > 0) {
            for (int i = 0; i < channelList.size(); i++) {
                if (i == 0) {
                    channelName = channelList.get(i);
                } else {
                    channelName += ("/" + channelList.get(i));
                }
            }
        }
        customers.setShareChannel(channelName);
        customersMapper.updateCustomers(customers);
        //删除查询条件
        delQueryModel(customersId);
        //保存新查询条件
        QueryModel queryModel = JSON.toJavaObject(queryCriteria, QueryModel.class);
        queryModel.setId(IDGenerator.gen());
        queryModel.setCustomersId(customers.getCustomersId());
        queryModel.setDimIds(JSON.toJSONString(queryModel.getFields()));
        queryModelMapper.addQueryModel(queryModel);
        //新增条件组
        String parentId = "-";
        setFilterGroup(customers.getCustomersId(), queryModel.getFilterGroup(), parentId,dateType);
    }

    /**
     * 查询单个客群详细信息
     *
     * @param customersId
     * @return
     */
    @Override
    public Customers findOneById(String customersId) {
        //客群信息
        Customers customers = customersMapper.findOneById(customersId);
        if (customers == null){
            return new Customers();
        }
        if (CustomersCodes.STATUS_01.equals(customers.getStatus())) {
            customers.setStatusName("有效");
        } else if (CustomersCodes.STATUS_02.equals(customers.getStatus())) {
            customers.setStatusName("失效");
        }
        if ("2".equals(customers.getApprovalStatus())) {
            customers.setApprovalStatusName("待审核");
        } else if ("3".equals(customers.getApprovalStatus())) {
            customers.setApprovalStatusName("驳回");
        } else if ("4".equals(customers.getApprovalStatus())) {
            customers.setApprovalStatusName("已通过");
        }
        //客群的渠道信息
        String channelName = "";
        List<String> channelList = customersMapper.findChannelByCustomersId(customersId);
        if (channelList != null && channelList.size() > 0) {
            for (int i = 0; i < channelList.size(); i++) {
                if (i == 0) {
                    channelName = channelList.get(i);
                } else {
                    channelName += ("/" + channelList.get(i));
                }
            }
        }
        customers.setShareChannel(channelName);
        //客群查询条件
        QueryModel queryModel = queryModelMapper.findOneQueryModel(customers.getCustomersId());
        setEsTime(queryModel,customers.getIndexId());
        queryModel.setFields(JSON.parseArray(queryModel.getDimIds(), String.class));
        if (queryModel.getFields() != null && !queryModel.getFields().isEmpty()) {
            String dimName = "";
            Map<String, String> dimMsg = new HashMap<>();
            for (String field : queryModel.getFields()) {
                //查出输出标签名
                dimName = queryModelMapper.findDimNameById(field);
                dimMsg.put(field, dimName);
            }
            queryModel.setDimMsg(dimMsg);
        }
        //查询filter列表
        List<Filter> filters = new ArrayList<>();
        List<FilterGroup> filterGroups = findFilterGroup("-", customersId, filters);
        queryModel.setFilterGroup(filterGroups.get(0));
        customers.setQueryModel(queryModel);
        //查询列表
        if (filters != null && !filters.isEmpty()) {
            Map<String, String> filtermap;
            for (Filter filter : filters) {
                filtermap = new HashMap<>();
                if (filter.getValueList() != null && !filter.getValueList()
                                                            .isEmpty()) {
                    String valueName = "";
                    for (String value : filter.getValueList()) {
                        Map<String, String> map = new HashMap<>();
                        map.put("dim_id", filter.getDimId());
                        map.put("item_no", value);
                        valueName = queryModelMapper.findValueName(map);
                        filtermap.put(value, valueName);
                    }
                }
                filter.setValueName(filtermap);
            }
            customers.setFilterList(filters);
        }
        return customers;
    }
    //动静态分开处理 动态：
    private void setEsTime(QueryModel queryModel,String indexId) {
        //这里主要处理详情回显客群的8位数据日期
        if (FieldHandler.pattern.matcher(queryModel.getFieldsDataDate()).matches() && queryModel.getFieldsDataDate().length() == FieldHandler.LENGTH8){
            String esTime = queryModelMapper.esRealTime(indexId);
            if (StringUtils.isNotEmpty(esTime)){
                queryModel.setFieldsDataDate(esTime);
            }
        }
    }

    /**
     * 获取我的客群列表
     *
     * @param pageNumber
     * @param pageSize
     * @param customersName
     * @param status
     * @param createTimeStart
     * @param createTimeEnd
     * @param uptTimeStart
     * @param uptTimeEnd
     * @param dateType
     * @return
     */
    @Override
    public Result myList(Integer pageNumber, Integer pageSize, String customersName, String status, String createTimeStart, String createTimeEnd, String uptTimeStart, String uptTimeEnd, String dateType) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Map map = new HashMap();
        map.put("userId", user.getUserId());
        map.put("customersName", customersName);
        map.put("approvalStatus", status);
        map.put("createTimeStart", createTimeStart);
        map.put("dateType", dateType);
        if (createTimeEnd != null && !"".equals(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd + "23.59.59");
        }
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<Customers> list = customersMapper.findMyList(map);
        //获取索引信息
        List<IndexInfoModel> allIndex = customersMapper.findAllIndex();
        Map<String, String> toMap = allIndex.stream().collect(Collectors.toMap(IndexInfoModel::getIndexId, IndexInfoModel::getIndexName));
        if (CollectionUtils.isEmpty(toMap)){
            toMap = new HashMap<>();
        }
        if (list != null && !list.isEmpty()) {
            for (Customers customers : list) {
                customers.setIndexName(toMap.get(customers.getIndexId()));
                if (CustomersCodes.STATUS_01.equals(customers.getStatus())) {
                    customers.setStatusName("有效");
                } else if (CustomersCodes.STATUS_02.equals(customers.getStatus())) {
                    customers.setStatusName("失效");
                }
                if ("1".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("未提交");
                } else if ("2".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("待审核");
                } else if ("3".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("驳回");
                } else if ("4".equals(customers.getApprovalStatus())) {
                    customers.setApprovalStatusName("已通过");
                }
                if (temp.compareTo(customers.getUptTime()) < 1) {
                    customers.setIsnew(true);
                } else {
                    customers.setIsnew(false);
                }
            }
        }
        CustomersPage<Customers> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(pageNumber);
        return new Result(CustomersCodes.SUCCESS, customersPage);
    }

    @Override
    //查询条件组
    public List<FilterGroup> findFilterGroup(String parentId, String customersId, List<Filter> filters) {
        Map<String, String> fgmap = new HashMap<>();
        fgmap.put("parentId", parentId);
        fgmap.put("customers_id", customersId);
        List<FilterGroup> filterGroupList = queryModelMapper.findFilterGroup(fgmap);
        Filter filter;
        List<Filter> filterList;
        if (filterGroupList != null && !filterGroupList.isEmpty()) {
            for (FilterGroup filterGroup : filterGroupList) {
                filterList = new ArrayList<>();
                //查找条件
                List<String> filterIds = queryModelMapper.findFilterIds(filterGroup.getId());
                if (filterIds != null && !filterIds.isEmpty()) {
                    for (String filterId : filterIds) {
                        filter = queryModelMapper.findOneFilterById(filterId);
                        //filter.setCnDateName(fetchCNDateName(filter));
                        filter.setValueList(JSON.parseArray(filter.getValueListStr(), String.class));
                        filterList.add(filter);
                        filters.add(filter);
                    }
                }
                filterGroup.setFilters(filterList);
                List<FilterGroup> list = findFilterGroup(filterGroup.getId(), customersId, filters);
                if (list != null && !list.isEmpty()) {
                    filterGroup.setChildren(list);
                }else{
                    filterGroup.setChildren(new ArrayList<FilterGroup>());
                }
            }
        }
        return filterGroupList;
    }

    private final static String CN_DATE_FORMAT = "当前月份%s";
    private static final String MONTH_FORMAT = "%s年%s月";
    private static final String zero = "0";

    private String fetchCNDateName(Filter filter) {
        if (filter.isTimeType()) {
            return zero.equals(filter.getDataDate()) ? String.format(CN_DATE_FORMAT, "") : String.format(CN_DATE_FORMAT, "-" + filter.getDataDate());
        } else {
            String year = StringUtils.substring(filter.getDataDate(), 0, 4);
            String month = StringUtils.substring(filter.getDataDate(), 4);
            return month.startsWith(zero) ? String.format(MONTH_FORMAT, year, month.substring(1)) : String.format(MONTH_FORMAT, year, month);
        }
    }

    /**
     * 根据dimId查找客群Ids
     *
     * @param dimId
     * @return
     */
    @Override
    public List<String> findCustomersIdsByDimId(String dimId) {
        List<String> customersIds = customersMapper.findCustomersIdsByDimId(dimId);
        return customersIds;
    }

    /**
     * 设置客群与渠道的关联关系
     *
     * @param customersId
     * @param shareChannelIds
     */
    public void setCustomersAndChannel(String customersId, String[] shareChannelIds) {
        if (shareChannelIds == null || shareChannelIds.length < 1) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        for (String channelId : shareChannelIds) {
            map.put("CUSTOMERS_ID", customersId);
            map.put("CHANNEL_ID", channelId);
            String id = IDGenerator.gen();
            map.put("id", id);
            customersMapper.setCustomersAndChannel(map);
        }
    }

    /**
     * 删除客群与渠道的关联关系
     *
     * @param customersId
     * @param customersId
     */
    public void delCustomersAndChannel(String customersId) {
        customersMapper.delCustomersAndChannel(customersId);
    }

    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void getCountAmount(Customers customers, QueryModel queryModel) {
        queryModel.setIndexId(customers.getIndexId());
        queryModel.setCustomersId(customers.getCustomersId());
        if (FieldHandler.FALSE.equals(customers.getDateType())){
            queryModel.setFieldTimeType(false);
        }else{
            queryModel.setFieldTimeType(true);
        }
        CustomerGroupRsp customerGroupRsp = queryService.customerGroup(JSONObject.toJSONString(queryModel));
        if(customerGroupRsp.getCode()==0){
            customers.setCustomerAmount(customerGroupRsp.getData().getTotalCount());
        }
    }

    @Override
    public int update(Customers customers) {
        return customersMapper.updateCustomers(customers);
    }

    @Override
    public Result sharedList(ListQueryModel model) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Map<String, String> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("customersName", model.getCustomersName());
        map.put("status", model.getStatus());
        map.put("createTimeStart", model.getCreateTimeStart());
        map.put("director", model.getDirector());
        if (model.getCreateTimeEnd() != null && !"".equals(model.getCreateTimeEnd())) {
            map.put("createTimeEnd", model.getCreateTimeEnd() + "23.59.59");
        }
        map.put("uptTimeStart", model.getUptTimeStart());
        if (model.getUptTimeEnd() != null && !"".equals(model.getUptTimeEnd())) {
            map.put("uptTimeEnd", model.getUptTimeEnd() + "23.59.59");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page<Object> page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
        List<Customers> list = customersMapper.findSharedList(map);

        //获取索引信息
        List<IndexInfoModel> allIndex = customersMapper.findAllIndex();
        Map<String, String> toMap = allIndex.stream().collect(Collectors.toMap(IndexInfoModel::getIndexId, IndexInfoModel::getIndexName));
        if (CollectionUtils.isEmpty(toMap)){
            toMap = new HashMap<>();
        }

        if (list != null && !list.isEmpty()) {
            for (Customers customers : list) {
                customers.setIndexName(toMap.get(customers.getIndexId()));
                if (CustomersCodes.STATUS_01.equals(customers.getStatus())) {
                    customers.setStatusName("有效");
                } else if (CustomersCodes.STATUS_02.equals(customers.getStatus())) {
                    customers.setStatusName("失效");
                }
                assert temp != null;
                customers.setIsnew(temp.compareTo(customers.getUptTime()) < 1);
                customers.setIsAnalysis(isAnalysis(customers.getDimIds()));
            }
        }
        CustomersPage<Customers> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(model.getPageNumber());
        return new Result(CustomersCodes.SUCCESS, customersPage);
    }

    @Override
    public Result privateList(ListQueryModel model) {
        //获取当前用户的id
        User user = TagSecurityHelper.currentUser();
        Map<String, String> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("customersName", model.getCustomersName());
        map.put("status", model.getStatus());
        map.put("createTimeStart", model.getCreateTimeStart());
        map.put("director", model.getDirector());
        map.put("dateType", model.getDateType());
        if (model.getCreateTimeEnd() != null && !"".equals(model.getCreateTimeEnd())) {
            map.put("createTimeEnd", model.getCreateTimeEnd() + "23.59.59");
        }
        map.put("uptTimeStart", model.getUptTimeStart());
        if (model.getUptTimeEnd() != null && !"".equals(model.getUptTimeEnd())) {
            map.put("uptTimeEnd", model.getUptTimeEnd() + "23.59.59");
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page<Object> page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
        List<Customers> list = customersMapper.findPrivateList(map);

        //获取索引信息
        List<IndexInfoModel> allIndex = customersMapper.findAllIndex();
        Map<String, String> toMap = allIndex.stream().collect(Collectors.toMap(IndexInfoModel::getIndexId, IndexInfoModel::getIndexName));
        if (CollectionUtils.isEmpty(toMap)){
            toMap = new HashMap<>();
        }

        if (!CollectionUtils.isEmpty(list)) {
            for (Customers customers : list) {
                customers.setIndexName(toMap.get(customers.getIndexId()));
                if (CustomersCodes.STATUS_01.equals(customers.getStatus())) {
                    customers.setStatusName("有效");
                } else if (CustomersCodes.STATUS_02.equals(customers.getStatus())) {
                    customers.setStatusName("失效");
                }
                assert temp != null;
                customers.setIsnew(temp.compareTo(customers.getUptTime()) < 1);
                customers.setIsAnalysis(isAnalysis(customers.getDimIds()));
            }
        }
        CustomersPage<Customers> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(model.getPageNumber());
        return new Result(CustomersCodes.SUCCESS, customersPage);
    }

    /**
     *
     * @param shareModel
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void give(ShareModel shareModel){
        String cid  = shareModel.getCustomersId();
        List<String> users  = shareModel.getUsers();

        if(StringUtils.equals(shareModel.getSharedState(),D_ZERO)){//撤销共享
            //关系表is_share=00 当所有共享关系撤销完毕时，tag-customers修改为未共享状态00
            if(CollectionUtils.isEmpty(users)){
                customersShareMapper.updIsShare(D_ZERO,cid,null);
                updateInfo(shareModel);
            }else{
                customersShareMapper.updIsShare(D_ZERO,cid,users);
                if(customersShareMapper.findExistByCid(cid)==0){
                    updateInfo(shareModel);
                }
            }
        }

        if(StringUtils.equals(shareModel.getSharedState(),D_ONE)){//共享所有
            shareModel.setUsers(Arrays.asList(ALL));
            List<String> existUserIds = customersShareMapper.findExistByCidAndUid(cid,Arrays.asList(ALL));
            if(CollectionUtils.isEmpty(existUserIds)){
                this.addRelations(shareModel);
            }else{
                customersShareMapper.updIsShare(D_ONE,cid,users);
            }
            updateInfo(shareModel);
        }

        if(StringUtils.equals(shareModel.getSharedState(), D_TWO)){//共享部分
            List<String> existUserIds = customersShareMapper.findExistByCidAndUid(cid,null);
            List<String> updUsers = users.stream().filter(existUserIds::contains).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(updUsers))customersShareMapper.updIsShare(D_ONE,cid,updUsers);
            List<String> addUsers = users.stream().filter(item->!existUserIds.contains(item)).collect(Collectors.toList());
            shareModel.setSharedState(D_ONE);
            shareModel.setUsers(addUsers);
            this.addRelations(shareModel);
            shareModel.setSharedState(D_TWO);
            updateInfo(shareModel);
        }

    }

    @Override
    public CustomersPage<ShareRelation> getShareList(ShareListQueryModel model){
        List<ShareRelation> shareList = new ArrayList<>();
        Page page = null;
        String sharedState = customersShareMapper.findShareStateByCustomersId(model.getCid());
        if(!D_TWO.equals(sharedState)){
            page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
            shareList = customersShareMapper.findExistAllByCid(model.getCid(), ALL);
        }else{
            page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
            shareList = customersShareMapper.findShareList(model.getCid());
            shareList.removeIf(e->e.getUserId().equals(ALL));
        }
//        if(CollectionUtils.isEmpty(shareList)){
//            page = PageHelper.startPage(model.getPageNumber(), model.getPageSize());
//            shareList = customersShareMapper.findShareList(model.getCid());
//        }
        CustomersPage<ShareRelation> sharePage = new CustomersPage<>();
        sharePage.setContent(shareList);
        sharePage.setTotalPages(page.getPages());
        sharePage.setTotalElements(page.getTotal());
        sharePage.setSize(page.getPageSize());
        sharePage.setRequestPager(model.getPageNumber());
        return sharePage;
    }

    private void addRelations(ShareModel shareModel){
        List<String> users = shareModel.getUsers();
        if(org.apache.commons.collections.CollectionUtils.isEmpty(users)){
            return;
        }
        List<ShareRelation> relations = new ArrayList<>(users.size());
        Date current = new Date();
        users.forEach(user->{
            relations.add(ShareRelation.of().setId(IdWorker.nextId()).setCustomersId(shareModel.getCustomersId()).setUserId(user).setCreateTime(current).setIsShare(D_ONE));
        });
        customersShareMapper.save(relations);
    }
    @Override
    public ShareModel sharedInfo(String customersId) {
        String sharedState = customersMapper.findSharedState(customersId);
        ShareModel model = new ShareModel();
        model.setCustomersId(customersId);
        model.setSharedState(sharedState);
        if(StringUtils.endsWith(sharedState, "02")){
            model.setUsers(customersShareMapper.findByCustomersId(customersId));
        }
        return model;
    }
    public void updateInfo(ShareModel shareModel){
        Customers data = new Customers();
        data.setCustomersId(shareModel.getCustomersId());
        data.setSharedState(shareModel.getSharedState());
        data.setUptTime(DateHelper.currentDateTime());
        customersMapper.shareUpdate(data);
    }

    @Override
    public CustomersPage<Customers> getDeployAndSeedCustomersByPage(int page, int size) {
        Page pageInfo = PageHelper.startPage(page, size);
        List<Customers> deployOrSeedCustomers = customersMapper.findDeployOrSeedCustomers();
        CustomersPage<Customers> customersPage = new CustomersPage<>();
        customersPage.setContent(deployOrSeedCustomers);
        customersPage.setTotalPages(pageInfo.getPages());
        customersPage.setTotalElements(pageInfo.getTotal());
        customersPage.setSize(pageInfo.getPageSize());
        customersPage.setRequestPager(page);
        return customersPage;
    }


}
